<template>
  <div class="app-container">
    <div class="box1">
      <button
      v-for="(item, index) in mallList"
      :key="'malls-' + index"
      class="custom-button"
      :class="{ active: selectedMalls === item }"
      @click="selectMalls(item)"
    >
      {{ item.name }}
    </button>
    </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="跟踪号" prop="trackingNumber">
        <el-input
          v-model="queryParams.trackingNumber"
          placeholder="请输入跟踪号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单创建时间" prop="orderProcessTimeRange">
        <el-date-picker
          v-model="queryParams.orderProcessTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="仓库名称" prop="warehouse">-->
<!--        <el-input-->
<!--          v-model="queryParams.warehouse"-->
<!--          placeholder="请输入仓库名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
    <el-form-item label="收件姓名" prop="receiverName">
        <el-input
          v-model="queryParams.receiverName"
          placeholder="请输入收件姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单子状态" prop="orderSubStatus" v-if="selectedMalls && selectedMalls.type=='Wildberries'">
        <el-select
          v-model="queryParams.orderSubStatus"
          placeholder="请选择订单子状态"
          @keyup.enter.native="handleQuery">
          <el-option label="waiting" value="waiting"></el-option>
          <el-option label="sorted" value="sorted"></el-option>
          <el-option label="sold" value="sold"></el-option>
          <el-option label="declined_by_client" value="declined_by_client"></el-option>
        </el-select>
      </el-form-item>
      <div class="box3">
        <el-radio-group v-model="selectedStatus" @change="handleRadioChange">
          <el-radio-button :label="0" class="radio-button-custom" :native-button="true">全部</el-radio-button>
          <el-radio-button :label="1" class="radio-button-custom" :native-button="true">未发送</el-radio-button>
          <el-radio-button :label="2" class="radio-button-custom" :native-button="true">发送成功</el-radio-button>
<!--          <el-radio-button :label="3" class="radio-button-custom" :native-button="true">取消发送</el-radio-button>-->
        </el-radio-group>
      </div>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" style="display: flex; align-items: center; margin-bottom: 10px;">
        <span style="font-size: 16px; font-weight: bold; color: #666666;">同步时间范围：</span>
        <el-select v-model="selectedTimeRange" placeholder="请选择时间范围" style="width: 150px; margin-left: 5px;">
          <el-option label="3天" value="3"></el-option>
          <el-option label="5天" value="5"></el-option>
          <el-option label="7天" value="7"></el-option>
          <el-option label="30天" value="30"></el-option>
        </el-select>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="isSyncing? 'el-icon-loading' : 'el-icon-refresh'"
          size="mini"
          @click="synchronousOrder"
          :disabled="isGettingNoodle"
        >同步订单</el-button>
      </el-col>
      <el-col :span="1.5" v-if="(selectOrderStatus === 'processing' || selectOrderStatus === 'waitingDelivery'|| selectOrderStatus === 'waitingDeliverys')">
        <el-button
          type="primary"
          plain
          :icon="isSyncings? 'el-icon-loading' : 'el-icon-refresh'"
          size="mini"
          @click="getNoodle"
        >获取面单</el-button>
      </el-col>
      <el-col :span="1.5" v-if="(selectOrderStatus === 'processing' || selectOrderStatus === 'waitingDelivery' ||  selectOrderStatus === 'waitingDelivery'|| selectOrderStatus === 'waitingDeliverys')">
        <el-button
          type="primary"
          plain
          icon="el-icon-position"
          size="mini"
          @click="sendOrder"
          :disabled="isGettingNoodle"
        >发送</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['erp:order:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <div style="background-color: #FFEDED; color: #ff4949; display: inline-block; padding: 5px; font-size: 13px">
        最后同步时间:{{sysTimeList && sysTimeList.syncTime? sysTimeList.syncTime : ''}}
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs v-model="selectOrderStatus" type="card" class="tab-status" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待商城处理" name="toUpload" v-if="selectedMalls && selectedMalls.type=='Ozon'"></el-tab-pane>
      <el-tab-pane label="等待备货" name="waitingStock" v-if="selectedMalls && selectedMalls.type=='Wildberries'"></el-tab-pane>
      <el-tab-pane label="待发送" name="processing" v-if="selectedMalls && selectedMalls.type=='Ozon'"></el-tab-pane>
      <el-tab-pane label="等待发货" name="waitingDelivery" v-if="selectedMalls && selectedMalls.type=='Wildberries'"></el-tab-pane>
      <el-tab-pane label="等待备货" name="waitingStocks" v-if="selectedMalls && selectedMalls.type=='Yandex'"></el-tab-pane>
      <el-tab-pane label="等待发货" name="waitingDeliverys" v-if="selectedMalls && selectedMalls.type=='Yandex'"></el-tab-pane>
      <el-tab-pane label="其他" name="other"></el-tab-pane>
    </el-tabs>
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="100" align="center" />
      <el-table-column label="序号" align="center" >
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺代号" align="center" prop="mallCode" />
      <el-table-column label="店铺订单编号" align="center" width="160">
        <template slot-scope="scope">
          <div>
            <span>{{ scope.row.orderNumber }}</span><br>
            <span>{{ scope.row.orderNumber01 }}</span><br>
            <span>{{ scope.row.orderNumber02 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单创建时间" align="center" prop="orderProcessTime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.orderProcessTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺订单状态" align="center" prop="orderStatus" />
      <el-table-column label="店铺订单子状态" align="center" prop="orderSubStatus" />
      <el-table-column label="仓库名称" align="center" prop="warehouse" />
      <el-table-column label="收件人姓名" align="center" prop="receiverName" />
      <el-table-column label="商品名称" align="center"  width="250">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.tbErpMallOrderItemList" :key="index">
            <el-tag
              :key="`tag-${index}`"
              type="info"
              style="max-width: 360px;height: auto; margin-left: 10px;margin-bottom: 5px; word-break: break-all; white-space: normal;display: inline-block"
              @click="getGoodDetails(scope.row)"
            >{{ item.goodSku + ',' + item.goodQuantity + 'pcs' + ((item.goodName)? ',' + item.goodName : '') }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最晚装包时间" align="center" prop="shipmentTime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.shipmentTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="派送时间" align="center" prop="deliveringTime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.deliveringTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发送仓库" align="center" prop="sendDepotCode" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.tbErpMallOrderSend">{{scope.row.tbErpMallOrderSend.sendDepotCode}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="发送人" align="center" prop="SendNameBy" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.tbErpMallOrderSend">{{scope.row.tbErpMallOrderSend.sendNameBy}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="发送时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.tbErpMallOrderSend">{{scope.row.tbErpMallOrderSend.sendTime}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="PDF" align="center" prop="erpLabel" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.tbErpMallOrderSend">{{scope.row.tbErpMallOrderSend.erpLabel}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="发送状态" align="center" prop="receiverCountry" fixed="right">
        <template slot-scope="scope">
          <span v-if="scope.row.tbErpMallOrderSend">{{scope.row.tbErpMallOrderSend.erpOrderStatus}}</span>
          <span v-else></span>
        </template>
        <template slot-scope="scope">
          <dict-tag v-if="scope.row.tbErpMallOrderSend" :options="dict.type.bizz_erp_order_status" :value="scope.row.tbErpMallOrderSend.erpOrderStatus"/>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="云仓返回单号" align="center" prop="depotNumber" width="180" fixed="right">
        <template slot-scope="scope">
          <span v-if="scope.row.tbErpMallOrderSend">{{scope.row.tbErpMallOrderSend.depotNumber}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150px">
        <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-printer"
                @click="printWay(scope.row)"
              >打印面单
              </el-button>
          <el-button
            v-if="(selectOrderStatus === 'processing' || selectOrderStatus === 'waitingDelivery' || selectOrderStatus==='waitingDeliverys')"
            size="mini"
            type="text"
            icon="el-icon-position"
            @click="sandOrder(scope.row)"
          >发送
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店铺订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺代号" prop="mallCode">
          <el-input v-model="form.mallCode" placeholder="请输入店铺代号" />
        </el-form-item>
        <el-form-item label="店铺订单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入店铺订单编号" />
        </el-form-item>
        <el-form-item label="店铺订单编号01" prop="orderNumber01">
          <el-input v-model="form.orderNumber01" placeholder="请输入店铺订单编号01" />
        </el-form-item>
        <el-form-item label="店铺订单编号02" prop="orderNumber02">
          <el-input v-model="form.orderNumber02" placeholder="请输入店铺订单编号02" />
        </el-form-item>
        <el-form-item label="跟踪号" prop="trackingNumber">
          <el-input v-model="form.trackingNumber" placeholder="请输入跟踪号" />
        </el-form-item>
        <el-form-item label="店铺订单创建时间" prop="orderProcessTime">
          <el-date-picker clearable
            v-model="form.orderProcessTime"
            type="date"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择店铺订单创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺订单价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入店铺订单价格" />
        </el-form-item>
        <el-form-item label="最晚装包时间" prop="shipmentTime">
          <el-date-picker clearable
            v-model="form.shipmentTime"
            type="date"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择最晚装包时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="派送时间" prop="deliveringTime">
          <el-date-picker clearable
            v-model="form.deliveringTime"
            type="date"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择派送时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="送达时间" prop="deliveryTime">
          <el-date-picker clearable
            v-model="form.deliveryTime"
            type="date"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择送达时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库id" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库id" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouse">
          <el-input v-model="form.warehouse" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodNames">
          <el-input v-model="form.goodNames" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="收件人姓名" prop="receiverName">
          <el-input v-model="form.receiverName" placeholder="请输入收件人姓名" />
        </el-form-item>
        <el-form-item label="收件国家" prop="receiverCountry">
          <el-input v-model="form.receiverCountry" placeholder="请输入收件国家" />
        </el-form-item>
        <el-form-item label="收件省州" prop="receiverProvince">
          <el-input v-model="form.receiverProvince" placeholder="请输入收件省州" />
        </el-form-item>
        <el-form-item label="收件城市" prop="receiverCity">
          <el-input v-model="form.receiverCity" placeholder="请输入收件城市" />
        </el-form-item>
        <el-form-item label="收件人地址" prop="receiverAddr">
          <el-input v-model="form.receiverAddr" placeholder="请输入收件人地址" />
        </el-form-item>
        <el-form-item label="收件邮编" prop="receiverPostcode">
          <el-input v-model="form.receiverPostcode" placeholder="请输入收件邮编" />
        </el-form-item>
        <el-form-item label="收件电话" prop="receiverPhone">
          <el-input v-model="form.receiverPhone" placeholder="请输入收件电话" />
        </el-form-item>
        <el-form-item label="收件手机" prop="receiverSms">
          <el-input v-model="form.receiverSms" placeholder="请输入收件手机" />
        </el-form-item>
        <el-form-item label="收件人证件" prop="receiverIdnumber">
          <el-input v-model="form.receiverIdnumber" placeholder="请输入收件人证件" />
        </el-form-item>
        <el-form-item label="收件人税号" prop="receiverTaxnumber">
          <el-input v-model="form.receiverTaxnumber" placeholder="请输入收件人税号" />
        </el-form-item>
        <el-form-item label="是否投保 默认否" prop="insuraned">
          <el-input v-model="form.insuraned" placeholder="请输入是否投保 默认否" />
        </el-form-item>
        <el-form-item label="删除标识" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标识" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--商品详情弹窗-->
    <el-dialog :title="ItemTitle" :visible.sync="orderItemOpen" width="1200px" append-to-body>
      <el-table v-loading="loading" :data="orderItemList" @selection-change="handleSelectionChange">
        <el-table-column label="" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品SKU" align="center" prop="goodSku" />
        <el-table-column label="产品编号" align="center" prop="goodProductId" />
        <el-table-column label="产品名称" align="center" prop="goodName" />
        <el-table-column label="产品数量" align="center" prop="goodQuantity" />
      </el-table>
    </el-dialog>

    <el-dialog :title="OrderSendTitle" :visible.sync="orderSendOpen" width="1200px" append-to-body @close="handleDialogClose">
      <div  v-loading="isSendingOrders" style="display: flex;">
        <el-table v-loading="loading" :data="orderItemList" @selection-change="handleSelectionChange" style="width: 500px; display: inline-block;">
          <el-table-column label="店铺订单编号" align="center" prop="orderNumber" />
        </el-table>
        <div style="display: inline-block; vertical-align: top; margin-left: 20px; display: flex">
          <div>
            <span>仓库：</span>
            <el-select placeholder="请选择仓库"  v-model="warehouseSelected"  @change="handleWarehouseChange">
              <el-option v-for="depot in depotList" :key="depot.name" :value="depot.name" />
            </el-select>
          </div>
          <div style="display: inline-block; vertical-align: top; margin-left: 10px;">
            <span>渠道：</span>
            <el-select  placeholder="请选择渠道" v-model="depotChannel">
              <el-option v-for="channel in channelList" :key="channel.channelName" :value="channel.channelName"/>
            </el-select>
          </div>
        </div>
      </div>
      <div style="text-align: right; margin-top: 10px;">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button type="primary" @click="cancels">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder,synchronousOrders,syncTime,getOrderItem,getFile,getDepotList,getChannel,getPrintList,sendOrders} from "@/api/erp/order";
import {getMall} from "@/api/erp/good"
export default {
  name: "Order",
  dicts: ['bizz_erp_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isSendingOrders: false,
      isPrintListFetching: false,
      isGettingNoodle: false,
      orderNumberArray:[],
      // 总条数
      total: 0,
      // 店铺订单表格数据
      orderList: [],
      //店铺数据
      mallList: [],
      //用于存储勾选的表格数据行
      selectedRows: [],
      isSyncing: false,
      isSyncings: false,
      depotNumber: null,
      channelName: null,
      selectedTimeRange:'3',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //商品详情弹窗
      orderItemOpen: null,
      //发送订单弹窗
      orderSendOpen:null,
      //发送订单标题
      OrderSendTitle:'',
      //商品详情标题
      ItemTitle: '',
      warehouseSelected:'',
      depotChannel:'',
      selectedStatus: 0,
      selectOrderStatus: 'all',
      selectedMalls: null,
      sysTimeList: [],
      orderItemList: [],
      depotList:[],
      channelList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        mallId: null,
        mallCode: null,
        orderNumber: null,
        orderNumber01: null,
        orderNumber02: null,
        trackingNumber: null,
        orderProcessTime: null,
        orderPrice: null,
        orderStatus: null,
        orderSubStatus: null,
        shipmentTime: null,
        deliveringTime: null,
        deliveryTime: null,
        warehouseId: null,
        warehouse: null,
        goodNames: null,
        receiverName: null,
        receiverCountry: null,
        receiverProvince: null,
        receiverCity: null,
        receiverAddr: null,
        receiverPostcode: null,
        receiverPhone: null,
        receiverSms: null,
        receiverIdnumber: null,
        receiverTaxnumber: null,
        insuraned: null,
        orderProcessTimeRange:[],
        orderProcessStartTime: '',
        orderProcessEndTime: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户ID不能为空", trigger: "blur"}
        ],
        mallId: [
          {required: true, message: "店铺ID不能为空", trigger: "blur"}
        ],
        orderNumber: [
          {required: true, message: "店铺订单编号不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        createBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    // this.getList();
    // this.getDepots()
  },
  methods: {
    /** 查询店铺订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancels(){
      this.orderSendOpen =false;
      this.orderItemList = [];
      this.warehouseSelected = [];
      this.depotChannel = [];
      this.orderNumberArray=[];
    },

    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        userId: null,
        mallId: null,
        mallCode: null,
        orderNumber: null,
        orderNumber01: null,
        orderNumber02: null,
        trackingNumber: null,
        orderProcessTime: null,
        orderPrice: null,
        orderStatus: null,
        orderSubStatus: null,
        shipmentTime: null,
        deliveringTime: null,
        deliveryTime: null,
        warehouseId: null,
        warehouse: null,
        goodNames: null,
        receiverName: null,
        receiverCountry: null,
        receiverProvince: null,
        receiverCity: null,
        receiverAddr: null,
        receiverPostcode: null,
        receiverPhone: null,
        receiverSms: null,
        receiverIdnumber: null,
        receiverTaxnumber: null,
        insuraned: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      const mallId = this.selectedMalls.mallId
      this.queryParams.mallId = mallId;
      if (this.queryParams.orderProcessTimeRange && this.queryParams.orderProcessTimeRange.length === 2) {
        // 将开始日期设置为当天的 00:00:00
        this.queryParams.orderProcessStartTime = `${this.queryParams.orderProcessTimeRange[0]} 00:00:00`;
        // 将结束日期设置为当天的 23:59:59
        this.queryParams.orderProcessEndTime = `${this.queryParams.orderProcessTimeRange[1]} 23:59:59`;
      } else {
        // 如果没有选择日期范围，清空开始和结束时间
        this.queryParams.orderProcessStartTime = '';
        this.queryParams.orderProcessEndTime = '';
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除店铺订单编号为"' + orderIds + '"的数据项？').then(function () {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    //获取店铺信息
    getMall() {
      this.loading = true;
      return getMall().then(response => {
        this.mallList = response.data
        this.loading = false;
        return response;
      })
    },
    //查询选中的店铺
    selectMalls(item) {
      this.selectedMalls = item;
      this.getNewTime()
      this.handleQuery()
    },
    //同步订单
    synchronousOrder() {
      if (!this.selectedTimeRange) {
        this.$modal.msgWarning("请先选择时间范围再进行同步");
        return;
      }
      this.isGettingNoodle=true
      this.isSyncing = true;
      const selectedMallInfo = this.selectedMalls
      const data = {
        appKey: selectedMallInfo.appKey,
        appSecret: selectedMallInfo.appSecret,
        type: selectedMallInfo.type,
        createDate: selectedMallInfo.createTime,
        code: selectedMallInfo.code,
        mallId: selectedMallInfo.mallId,
        day:this.selectedTimeRange
      }
      synchronousOrders(data).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("同步订单成功 共" + response.data + "条数据")
        }
        this.isSyncing = false;
        this.isGettingNoodle=false;
        this.getList()
        this.getNewTime()
      }).catch(() => {
        this.$modal.msgError("同步订单失败")
        this.isSyncing = false;
      })
    },
    //获取最新的同步时间
    getNewTime() {
      const mallId = this.selectedMalls.mallId
      const syncType = '1'
      syncTime(mallId, syncType).then(response => {
        this.sysTimeList = response.data
      })
    },
    //获取商品详情
    getGoodDetails(row) {
      const orderNumber = row.orderNumber;
      const mallId = row.mallId;
      getOrderItem(mallId, orderNumber).then(response => {
        this.orderItemList = response.data
        this.ItemTitle = "订单明细共" + this.orderItemList[0].totalCount + "条"
        this.orderItemOpen = true;
      })
    },
    getDepots(){
      getDepotList().then(response =>{
        this.depotList =response.data
      })
    },
    //打印面单
    printWay(row) {
      const selectedMallInfo = this.selectedMalls;
      const data = {
        appKey: selectedMallInfo.appKey,
        appSecret: selectedMallInfo.appSecret,
        type: selectedMallInfo.type,
        mallId: row.mallId,
        orderNumber: row.orderNumber,
        orderNumber01:row.orderNumber01
      };
      getFile(data).then(response => {
        const url = response
        if (url) {
          const newWindow = window.open(url, 'newWindow');
          if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
            this.$message.error("无法打开新窗口展示面单，请检查浏览器设置");
          }
        } else {
          this.$message.warning("获取面单失败，未获取到有效的URL");
        }
      }).catch(error => {
        // 在这里可以添加更详细的错误处理逻辑，比如打印具体错误信息等
        console.error("获取面单出现错误:", error);
        this.$message.error("获取面单时发生错误，请稍后再试");
      });
    },
    handleRadioChange() {
      if (!this.queryParams) {
        this.queryParams = {};
      }
      const statusMap = {
        1: '1',
        2: '2',
        3: '3'
      };
      if (this.selectedStatus === 0) {
        delete this.queryParams.erpOrderStatus;
      } else {
        this.queryParams.erpOrderStatus = statusMap[this.selectedStatus] || '';
      }
      this.handleQuery();
    },
    handleTabClick(tab) {
      if (!this.queryParams) {
        this.queryParams = {};
      }
      const statusMap = {
        'all': '',
        'toUpload': 'awaiting_packaging',
        'waitingStock': 'awaiting_packaging',
        'waitingStocks': 'PROCESSING',
        'processing': 'awaiting_deliver',
        'waitingDelivery': 'complete',
        'other': '5'
      };
      if (tab.name === 'all') {
        delete this.queryParams.orderStatus;
        delete this.queryParams.erpOrderStatus;
        delete this.queryParams.orderSubStatus;
      } else {
        this.queryParams.orderStatus = statusMap[tab.name] || '';
      }

      if (this.selectedMalls && this.selectedMalls.type === 'Yandex') {
        if (tab.name === 'waitingStocks') {
          this.queryParams.orderSubStatus = 'PROCESSING_SUB_STATUS';
        }
        if (tab.name === 'waitingDeliverys') {
          this.queryParams.orderSubStatus = 'READY_TO_SHIP';
          this.queryParams.erpOrderStatus = '1';
        }
        // // 删除 erpOrderStatus
        // delete this.queryParams.erpOrderStatus;
      } else {
        if (tab.name === 'processing') {
          this.queryParams.erpOrderStatus = '1';
        }
        if (tab.name === 'waitingDelivery') {
          this.queryParams.erpOrderStatus = '1';
        }
        // 删除 orderSubStatus
        delete this.queryParams.orderSubStatus;
      }

      this.handleQuery();
    },
    handleDateChange(value){
      if (value && value.length === 2) {
        this.queryParams.orderProcessStartTime = `${value[0]} 00:00:00`;
        this.queryParams.orderProcessEndTime = `${value[1]} 23:59:59`;
      } else {
        this.queryParams.orderProcessStartTime = '';
        this.queryParams.orderProcessEndTime = '';
      }
      this.handleQuery();
    },
    // handleTabClick(tab) {
    //   if (!this.queryParams) {
    //     this.queryParams = {};
    //   }
    //   const statusMap = {
    //     'all': '',
    //     'toUpload': 'awaiting_packaging',
    //     'waitingStock': 'awaiting_packaging',
    //     'waitingStocks': 'PROCESSING',
    //     'processing': 'awaiting_deliver',
    //     'waitingDelivery': 'complete',
    //     'waitingDeliverys': 'PICKUP',
    //     'other': '5'
    //   };
    //   if (tab.name === 'all') {
    //     delete this.queryParams.orderStatus;
    //   } else {
    //     this.queryParams.orderStatus = statusMap[tab.name] || '';
    //   }
    //   if (tab.name === 'processing') {
    //     this.queryParams.erpOrderStatus = '1';
    //   }
    //   if (tab.name === 'waitingDelivery') {
    //     this.queryParams.erpOrderStatus = '1';
    //   }
    //   this.handleQuery();
    // },
    //发送订单
    sandOrder(row){
     this.orderSendOpen=true;
     this.OrderSendTitle='订单发送'
     const newItem ={
       orderNumber:row.orderNumber,
     }
     this.orderItemList.push(newItem)
      this.orderNumberArray.push(row.orderNumber);
      let orderNumber = this.orderNumberArray.slice();
      const data ={
       appKey:this.selectedMalls.appKey,
       appSecret:this.selectedMalls.appSecret,
        type:this.selectedMalls.type,
        mallId:this.selectedMalls.mallId,
        orderNumbers: orderNumber
      }
      this.isPrintListFetching = true;
      getPrintList(data).then(response =>{
        if(response.code ===200){
          this.$message.success("获取面单成功")
          this.isPrintListFetching = false;
        }
      })
    },
    handleWarehouseChange(value){
      const selectedDepot = this.depotList.find(depot => depot.name === value);
      if(selectedDepot){
        const depotCode =selectedDepot.depotCode;
        getChannel(depotCode).then(response=>{
          this.channelList=response.data;
        })
      }
    },
    //批量发送订单
    sendOrder(){
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择需要发送订单的数据");
        return;
      }
      this.selectedRows.forEach((row) =>{
        const  newItem ={
          orderNumber:row.orderNumber,
        }
        this.orderItemList.push(newItem)
      })
      const orderNumbers = this.orderItemList.map(item => item.orderNumber);
      this.orderSendOpen=true;
      const data={
        appKey:this.selectedMalls.appKey,
        appSecret:this.selectedMalls.appSecret,
        type:this.selectedMalls.type,
        mallId:this.selectedMalls.mallId,
        orderNumbers:orderNumbers
      }
      this.isPrintListFetching = true;
      // getPrintList(data).then(response =>{
      //   if(response.code ===200){
      //     this.$message.success("获取面单成功")
      //     this.isPrintListFetching = false;
      //   }
      // })
    },
    getNoodle(){
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择需要获取面单的数据");
        return;
      }
      this.isGettingNoodle = true;
      this.isSyncings=true;
      this.selectedRows.forEach((row) =>{
        const  newItem ={
          orderNumber:row.orderNumber,
        }
        this.orderItemList.push(newItem)
      })
      const orderNumbers = this.orderItemList.map(item => item.orderNumber);
      const data={
        appKey:this.selectedMalls.appKey,
        appSecret:this.selectedMalls.appSecret,
        type:this.selectedMalls.type,
        mallId:this.selectedMalls.mallId,
        orderNumbers:orderNumbers
      }
      getPrintList(data).then(response =>{
        if(response.code ===200){
          this.$message.success("获取面单成功")
          this.orderItemList = [];
        }
        this.isSyncings=false;
        this.isGettingNoodle = false;
      }).catch(() =>{
        this.$modal.msgError("获取面单失败")
        this.isSyncings=false
        this.isGettingNoodle = false;
      })
    },
    //发送订单
    handleConfirm() {
      if (this.warehouseSelected.length === 0) {
        this.$message.warning("请选择仓库");
        return;
      }
      // 检查渠道是否选择，未选择则提示
      if (this.depotChannel.length === 0) {
        this.$message.warning("请选择渠道");
        return;
      }

      const orderNumbers = this.orderItemList.map(item => item.orderNumber);
      const depot = this.warehouseSelected;
      const channel = this.depotChannel;

      // 获取仓库对应的depotId
      const selectedDepot = this.depotList.find(item => item.name === depot);
      const depotId = selectedDepot?.depotId;
      if (!depotId) {
        this.$message.error("无法获取有效的仓库ID，请检查仓库选择");
        return;
      }
      const selectedChannel = this.channelList.find(item => item.channelName === channel);
      const subscribeDepotCode = selectedChannel?.subscribeDepotCode;
      if (!subscribeDepotCode) {
        this.$message.error("无法获取有效的渠道编码，请检查渠道选择");
        return;
      }
      const data = {
        orderNumbers: orderNumbers,
        depotId: depotId,
        depot: subscribeDepotCode,
        channel: channel,
        type: this.selectedMalls.type,
        mallId: this.selectedMalls.mallId
      };
      this.isSendingOrders = true;
      sendOrders(data).then(response => {
        this.isSendingOrders = false;
        if (response && response.msg) {
          const h = this.$createElement;
          this.$msgbox({
            title: '订单发送结果',
            message: h('div', {
              domProps: {
                innerHTML: response.msg
              }
            }),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            this.orderItemList = [];
            this.orderSendOpen = false;
            this.warehouseSelected = [];
            this.depotChannel = [];
            this.getList();
          }).catch(() => {
          });
        } else {
          this.$message.error("订单发送失败");
        }
      }).catch(error => {
        this.isSendingOrders = false;
        this.$message.error(`订单发送出现错误：${error.message || '未知错误'}`);
      });
    },
    handleDialogClose(){
      this.orderItemList = [];
    }
  },
    mounted() {
    this.getMall().then(()=>{
      this.selectedMalls=this.mallList[0];
      this.getNewTime()
      this.handleQuery()
      this.getDepots()
    })
  }
};
</script>
<style>
.button-container {
  display: flex; /* 使用 Flexbox 来排列按钮 */
}

.custom-button {
  background-color: transparent;
  color: rgba(0,0,0,0.6); /* 默认文字颜色为黑色 */
  border: 0.2px solid rgba(0, 0, 0, 0.3);
  padding: 3px 3px;
  font-size: 16px;
  transition: background-color 0.3s, color 0.3s, border-color 0.3s;
  min-width: 80px; /* 设置按钮的最小宽度 */
  min-height: 40px; /* 设置按钮的最小高度 */
  display: inline-flex; /* 使按钮大小根据内容调整 */
  align-items: center; /* 垂直居中对齐文字 */
  justify-content: center; /* 水平居中对齐文字 */

}

.custom-button:hover {
  background-color: white; /* 悬停时背景颜色保持白色 */
  color: #1890FF; /* 悬停时文字颜色变为蓝色 */
}

.custom-button:active{
  background-color: white;
  color: black;
}
.custom-button:focus {
  background-color: #1890FF; /* 点击或选中时背景颜色变为蓝色 */
  color: white; /* 点击或选中时文字颜色变为白色 */
  border-color: dodgerblue; /* 点击或选中时边框颜色变为蓝色 */
}

.custom-button:not(:last-of-type) {
  border-right: none; /* 去掉按钮之间的右边框 */
}
.active {
  background-color: dodgerblue;
  color: white;
}
.box1{
  margin-bottom: 20px;
}
.radio-button-custom {
  background-color: transparent; /* 初始背景色设为透明 */
  margin-bottom: 2px;
}
.radio-button-custom.el-radio-button__inner.is-checked {
  background-color: #1890ff; /* 选中时背景色设为蓝色，可根据需求调整颜色值 */
  color: white; /* 文字颜色设为白色，也可按需调整 */
}
.tab-status {
  margin-bottom: 10px; /* 调整与下方表格的间距 */
}
/* 去除el-tabs的边框样式 */
.tab-status.el-tabs__header {
  border: none;
}
.tab-status.el-tabs__nav {
  border-bottom: none;
}
.tab-status.el-tabs__nav-wrap::after {
  border-bottom-color: transparent;
}
.tab-status.el-tabs__item {
  border: none;
}
</style>
